import { defineConfig } from 'vite'
import vue2 from '@vitejs/plugin-vue2'
import path from 'path'
import { loadEnv } from 'vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig(({ command, mode }) => {

    const env = loadEnv(mode, process.cwd());
    return {
        server: {
            // 允许IP访问
            host: "0.0.0.0",
            // 应用端口 (默认:3000)
            port: Number(env.VITE_APP_PORT),
            // 运行是否自动打开浏览器
            open: false,
            proxy: {
              /** 代理前缀为 /dev-api 的请求  */
              [env.VITE_APP_BASE_API]: {
                changeOrigin: true,
                // 接口地址
                target: env.VITE_APP_API_URL,
                rewrite: (path) =>
                  path.replace(new RegExp("^" + env.VITE_APP_BASE_API), ""),
              },
              // 添加音频文件代理，解决CORS问题
              '/api/proxy-audio': {
                target: 'http://39.108.92.96',
                changeOrigin: true,
                rewrite: (path) => {
                  const url = new URLSearchParams(path.split('?')[1]).get('url');
                  if (url) {
                    try {
                      const parsedUrl = new URL(url);
                      return parsedUrl.pathname + (parsedUrl.search || '');
                    } catch (e) {
                      console.error('解析URL失败:', e);
                      return path;
                    }
                  }
                  return path;
                },
                configure: (proxy, options) => {
                  // 修改响应头，允许跨域
                  proxy.on('proxyRes', function(proxyRes, req, res) {
                    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
                    // 始终添加正确的内容类型
                    const format = new URLSearchParams(req.url.split('?')[1]).get('format');
                    if (format === 'mp3') {
                      proxyRes.headers['content-type'] = 'audio/mpeg';
                    } else if (format === 'ogg') {
                      proxyRes.headers['content-type'] = 'audio/ogg';
                    } else if (format === 'wav') {
                      proxyRes.headers['content-type'] = 'audio/wav';
                    } else if (format === 'webm') {
                      proxyRes.headers['content-type'] = 'audio/webm';
                    }
                  });
                }
              },
            },
        },
        plugins: [
          vue2(),
          createSvgIconsPlugin({
            // 指定需要缓存的图标文件夹
            iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
            // 指定symbolId格式
            symbolId: 'icon-[dir]-[name]',
          }),
        ],
        resolve: {
          alias: {
            '@': path.resolve(__dirname, './src')
          }
        },
        css: {
            preprocessorOptions: {
              scss: {
                api: 'modern-compiler',
                additionalData: `
                  @import "@/styles/variables.scss";
                  @import "@/styles/mixins.scss";
                  @import "@/styles/global.scss";
                  @import "@/styles/elmentui.scss";
                `
              }
            }
        }
    }
  
})
